package com.ft.oa.service.project.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.Attachment;
import com.ft.oa.domain.approval.ApplyForApproval;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.project.BidProject;
import com.ft.oa.domain.project.BidProjectPage;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.attachment.AttachmentMapper;
import com.ft.oa.mapper.bidProjectMapper.BidProjectMapper;
import com.ft.oa.mapper.clueprojectMapper.ClueProjectMapper;
import com.ft.oa.mapper.sys.SysDeptMapper;
import com.ft.oa.mapper.sys.SysUserMapper;
import com.ft.oa.service.approval.ApplyForApprovalService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.service.project.BidProjectService;
import com.ft.oa.utils.FileUtil;
import com.ft.oa.utils.SecurityUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 招投标管理接口
 * @author liyansheng
 * @ClassName BidProjectServiceImpl
 * @date 2022-1-5 16:09:29
 */
@Service
public class BidProjectServiceImpl implements BidProjectService {
    //附件上传位置
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @Resource
    private BidProjectMapper bidProjectMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ClueProjectMapper clueProjectMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private ApplyForApprovalService applyForApprovalService;

    @Resource
    private DirectoryService directoryService;
    /**
     * 新增招投标项目
     * @param bidProject
     * @return
     */
    @Override
    @Transactional
    public ApiResult add(BidProject bidProject) {
        List<AttachmentDto> attachments = bidProject.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String json = JSONArray.toJSONString(attachments);
            bidProject.setAchment(json);
        }else{
            bidProject.setAchment(null);
        }
        bidProjectMapper.insert(bidProject);
        /**
         * 保存附件项目相关的公共方法
         *
         * @param attachments 附件集合
         * @param source      来源  根据 DirectoryTypeEnum
         * @param relationId  业务id
         * @param sourceId    如果一个表单有多个附件，用于标识附件属于表单的哪个附件
         * @param  projectNumber 项目编号 全局唯一
         */
        directoryService.saveProAttachment(bidProject.getAttachments(), DirectoryTypeEnum.PRO_FD_BID.getCode(),String.valueOf(bidProject.getId()),null,bidProject.getProjectNumber());

        //审批人
        List<ApplyForApproval> bidCheckList = bidProject.getBidCheckList();
        if(bidCheckList!=null&&bidCheckList.size()>0){
            bidCheckList.forEach(e->{
                //业务表主键
                e.setRelationId(bidProject.getId());
                //业务表编码（非必填）
                e.setRelationCode(bidProject.getProjectNumber());
                /**
                 * 关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
                 * 6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
                 */
                e.setRelationType(3);
            });
            applyForApprovalService.addApproval(bidCheckList);
        }
        //抄送人
        List<ApplyForApproval> bidCopyList = bidProject.getBidCopyList();
        if(bidCopyList!=null&&bidCopyList.size()>0){
            bidCopyList.forEach(e->{
                //业务表主键
                e.setRelationId(bidProject.getId());
                //业务表编码（非必填）
                e.setRelationCode(bidProject.getProjectNumber());
                /**
                 * 关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
                 * 6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
                 */
                e.setRelationType(3);
            });
            applyForApprovalService.addCarbonCopy(bidCopyList);
        }
        return ApiResult.simpleSuccess();
    }

    /**
     * 修改招投标项目
     * @param bidProject
     * @return
     */
    @Override
    @Transactional
    public ApiResult edit(BidProject bidProject) {
        //bidProject.setEditor(SecurityUtils.getCurrentUser().getId());
        bidProject.setId(bidProject.getId());
        bidProject.setUpdateTime(LocalDate.now());
        bidProjectMapper.updateById(bidProject);
        return ApiResult.simpleSuccess();
    }

    /**
     * 删除招投标项目
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ApiResult del(Long id) {
        LambdaUpdateChainWrapper<BidProject> wrapper = new LambdaUpdateChainWrapper<BidProject>(bidProjectMapper);
        wrapper.eq(BidProject::getId,id)
                .set(BidProject::getDellbid,"1")
                .update();
        return ApiResult.simpleSuccess();
    }

    /**
     * 根究主键查询招投标项目
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ApiResult selectById(Long id) {
        BidProject bidProject = bidProjectMapper.selectById(id);
        String achment = bidProject.getAchment();
        bidProject.setAchment("");
        bidProject.setAttachments(JSONObject.parseArray(achment, AttachmentDto.class));
        // 项目线索名称
        bidProject.setRelatedProjectCues(clueProjectMapper.selectById(bidProject.getRelatedProjectCuesId()).getXsname());
        //项目线索编号
        bidProject.setProjectNumber(clueProjectMapper.selectById(bidProject.getRelatedProjectCuesId()).getProjectNumber());
        //商务负责人
        bidProject.setCommercialOfficer(sysUserMapper.selectById(bidProject.getCommercialOfficerId()).getNickname());
        //投标负责人 bidder
        bidProject.setBidder(sysUserMapper.selectById(bidProject.getBidderId()).getNickname());
        //technicalDirector	技术负责人
        bidProject.setTechnicalDirector(sysUserMapper.selectById(bidProject.getTechnicalDirectorId()).getNickname());
        bidProject.setBidDepartmenter(sysDeptMapper.selectById(bidProject.getBidDepartmenterId()).getName());
        //审批人
        bidProject.setBidCheckList(applyForApprovalService.selectApprovalUser(bidProject.getId(),3));
        //抄送人
        bidProject.setBidCopyList(applyForApprovalService.selectCopyUser(bidProject.getId(),3));
        return ApiResult.successWithData(bidProject);
    }

    /**
     * 修改招投标结果
     * @param  、bidResult
     * @return
     */
    @Override
    @Transactional
    public ApiResult changeBidResult(BidProjectPage bidProjectPage) {
        UpdateWrapper<BidProject> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",bidProjectPage.getId());
        updateWrapper.set("bid_result",bidProjectPage.getBidResult());
        updateWrapper.set("creator", SecurityUtils.getCurrentUser().getId());
        updateWrapper.set("update_time",LocalDateTime.now());
        updateWrapper.set("money",bidProjectPage.getMoney());
        updateWrapper.set("pbscore",bidProjectPage.getPbscore());
        updateWrapper.set("dbtime",bidProjectPage.getDbtime());
        updateWrapper.set("fbtime",bidProjectPage.getFbtime());
        List<AttachmentDto> attachments = bidProjectPage.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String achment = JSONArray.toJSONString(attachments);
            updateWrapper.set("achment",achment);
        }
        int update = bidProjectMapper.update(null, updateWrapper);
        /**
         * 保存附件项目相关的公共方法
         *
         * @param attachments 附件集合
         * @param source      来源  根据 DirectoryTypeEnum
         * @param relationId  业务id
         * @param sourceId    如果一个表单有多个附件，用于标识附件属于表单的哪个附件
         * @param  projectNumber 项目编号 全局唯一
         */
        directoryService.saveProAttachment(bidProjectPage.getAttachments(), DirectoryTypeEnum.PRO_FD_BID.getCode(),String.valueOf(bidProjectPage.getId()),null,bidProjectPage.getProjectNumber());

        return ApiResult.successWithData(update);
    }

    /**
     * 分页查询招投标数据
     * @param bidpage
     * @return
     */
    @Override
    public ApiResult page(BidProjectPage bidpage) {
        QueryWrapper<BidProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(bidpage.getBidResult()!=null&&bidpage.getBidResult()>=0,BidProject::getBidResult,bidpage.getBidResult())
                //.eq(bidpage.getToProject()==0,BidProject::getToProject,bidpage.getToProject())//待立项分页条件。招投标不用此查询条件
                .eq(BidProject::getDellbid,"0")
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()),BidProject::getCreator,SecurityUtils.getCurrentUser().getId())
                .like(StringUtils.hasText(bidpage.getBidName()),BidProject::getBidName,bidpage.getBidName())
                .like(StringUtils.hasText(bidpage.getRelatedProjectCues()),BidProject::getRelatedProjectCues,bidpage.getRelatedProjectCues());
        Page<BidProject> page = new Page<>(bidpage.getPage(),bidpage.getSize());
        IPage<BidProject> pages = bidProjectMapper.selectPage(page,queryWrapper.orderByDesc("create_time"));
        List<BidProject> records = pages.getRecords();
        records.forEach(bidProject ->{
            //商务负责人
            bidProject.setCommercialOfficer(sysUserMapper.selectById(bidProject.getCommercialOfficerId()).getNickname());
            //投标负责人 bidder
            bidProject.setBidder(sysUserMapper.selectById(bidProject.getBidderId()).getNickname());
            //technicalDirector	技术负责人
            bidProject.setTechnicalDirector(sysUserMapper.selectById(bidProject.getTechnicalDirectorId()).getNickname());
            // 项目线索名称
            bidProject.setRelatedProjectCues(clueProjectMapper.selectById(bidProject.getRelatedProjectCuesId()).getXsname());
            //项目线索编号
            bidProject.setProjectNumber(clueProjectMapper.selectById(bidProject.getRelatedProjectCuesId()).getProjectNumber());
        });
        return ApiResult.successWithData(pages);
    }


    /**
     * 附件上传记录
     * @param files
     * @return
     */
    @Override
    @Transactional
    public ApiResult upload(MultipartFile files[],String source) {
        //记录文件上传信息
        ArrayList<Attachment> fileList = new ArrayList<Attachment>();
        for (MultipartFile myFile:files) {
            Attachment attachment = new Attachment();
            // 获取文件名称
            String filename = FilenameUtils.getBaseName(myFile.getOriginalFilename());
            //获取后缀名称
            String ext = FilenameUtils.getExtension(myFile.getOriginalFilename());
            String rebuildFileName = filename+System.currentTimeMillis();
            attachment.setName(filename);
            attachment.setFileName(rebuildFileName);
            attachment.setType(ext);
            attachment.setSource(source);
            attachment.setPath(uploadFilePath);
            attachmentMapper.insert(attachment);
            fileList.add(attachment);
        }
        //调用公共方法上传附件
        HashMap<String, List<String>> hashMap = FileUtil.getFileUpload(files, uploadFilePath);
        if(hashMap.isEmpty()){
            return ApiResult.builder().msg("文件上传失败").build();
        }else{
            //上传成功后把附件表主键信息传给前端
            List<Long> resultList = fileList.stream().map(Attachment::getId).collect(Collectors.toList());
            String uploadIds = org.apache.commons.lang3.StringUtils.join(resultList.toArray(),",");
            return ApiResult.successWithData(uploadIds);
        }
    }

    @Override
    public int approvalstatus(BidProjectPage bidpage) {
        UpdateWrapper<BidProject> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",bidpage.getId());
        updateWrapper.set("approval_status",bidpage.getApprovalstatus());
        updateWrapper.set("creator", SecurityUtils.getCurrentUser().getId());
        updateWrapper.set("update_time",LocalDateTime.now());
        updateWrapper.set("remarks",bidpage.getRemarks());
        return bidProjectMapper.update(null, updateWrapper);
    }


}
